//
//  EDHomeViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/4.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDHomeViewController.h"
#import "EDHomeTableHeadView.h"
#import "HomeModel.h"
#import "HomeTableViewCell.h"
#import "HomeHeadTableViewCell.h"
#import "LLWebViewController.h"
#import "AppDelegate.h"
#import "AnnouncementViewController.h"
#import "MailMainViewController.h"
#import "NoticeMessageVC.h"

#define headViewHeight RealValue_H(440)
@interface EDHomeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;//
@property (nonatomic, strong) NSMutableArray * newsArray;//新闻公告
@property (nonatomic, strong) NSMutableArray * banneArray;//数组图片
@property (nonatomic, strong) NSString * balance;
@property (nonatomic,strong) EDHomeTableHeadView * tableviewHeadView;
@end

@implementation EDHomeViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self statusBarStyleIsDark:YES];
    [ self.navigationController.navigationBar setBackgroundImage:[self createImageWithColor:CLEARCOLOR frame:CGRectMake(0, 0, UIScreenWidth,kStatusBarAndNavigationBarHeight)] forBarMetrics:UIBarMetricsDefault];
    [ self.navigationController.navigationBar setShadowImage:[UIImage new]];
}
- (void)viewDidAppear:(BOOL)animated
{
    [self getWallet];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self statusBarStyleIsDark:NO];
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kStatusBarAndNavigationBarHeight)];
    UIImageView *backViewimage = [BBControl createImageViewFrame:CGRectMake(0, 0, kScreenWidth, kStatusBarAndNavigationBarHeight) imageName:@"barImage"];
    backViewimage.contentMode = UIViewContentModeScaleToFill;
    [backView addSubview:backViewimage];
    
    [self.navigationController.navigationBar  setBackgroundImage:[self convertViewToImage:backView] forBarMetrics:UIBarMetricsDefault];

    
}
-(UIImage*)convertViewToImage:(UIView*)v{
    CGSize s = v.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需  要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, YES, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
//根据颜色值生成纯色图片
- (UIImage *)createImageWithColor:(UIColor *)color frame:(CGRect)frame {
    CGRect rect = CGRectMake(0, 0, frame.size.width, frame.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
    [self.view addSubview:self.tableView];
    self.navigationItem.title = @"";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem LeftitemWithImageNamed:@"icon_youhui.png" title:@"" target:self action:@selector(build)];
    self.navigationItem.titleView=self.leftlogin;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:self.rightItem];
    _dataArray = [[NSMutableArray alloc] init];
    _newsArray = [[NSMutableArray alloc] init];
    _banneArray = [[NSMutableArray alloc] init];
    [self getNewslist];
    [self getbanner];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginOutSusess) name:ExitLogonNotificationse object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registeredSusess) name:@"registeredSusessNotificationse" object:nil];
    
    
}
- (void)build
{
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APIName:@"m/promotion_list.html"];
    LLWebViewController * webview = [[LLWebViewController alloc] init];
    webview.urlStr = url;
    webview.isType = 1;
    webview.titleStr = @"优惠活动";
    [self.navigationController pushViewController:webview animated:YES];
    
}
-(void)LoginOutSusess{
    [self getWallet];
}
- (void)LoginSusess
{
    [self getWallet];
}

- (void)registeredSusess
{
        WEAKSELF
    [[SmileAlert sharedInstance] registered_alertContent:@"" AndBlock:^(BOOL sure) {
        STRONGSELFFor(weakSelf);
        if (sure==YES) {
            YYLog(@"点击立即领取，需要跳转到我的页面");
            AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            appDelegate.is_RegisteredAlert = YES;//注册弹框的显示红色客服
            strongSelf.navigationController.tabBarController.selectedIndex = 4;
        }
    }];
    
}


- (UIImageView *)leftlogin
{
    UIImageView *leftlogin=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,RealValue_W(250), RealValue_W(42))];
    leftlogin.image = [UIImage imageNamed:@"logo_dark"];
    return leftlogin;
}
- (UIView *)rightItem
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    view.backgroundColor = [UIColor clearColor];
    UIButton * chatbutton = [[UIButton alloc] initWithFrame:CGRectMake(40, 0, 40, 30)];
    [chatbutton setImage:[UIImage imageNamed:@"homeChat"] forState:UIControlStateNormal];
    
    [chatbutton addTarget:self action:@selector(chatbutton) forControlEvents:UIControlEventTouchUpInside];
    [chatbutton sizeToFit];
    chatbutton.centerY = view.centerY;
    [view addSubview:chatbutton];
    UIButton * messagebutton = [[UIButton alloc] initWithFrame:CGRectMake(90, 0, 40, 30)];
    [messagebutton setImage:[UIImage imageNamed:@"homemessage"] forState:UIControlStateNormal];
    [messagebutton setImage:[UIImage imageNamed:@"homemessage"] forState:UIControlStateSelected];
    [messagebutton addTarget:self action:@selector(messageClick) forControlEvents:UIControlEventTouchUpInside];
    [messagebutton sizeToFit];
    messagebutton.centerY = view.centerY;
    [view addSubview:messagebutton];
    return view;
}
//联系客户
- (void)chatbutton
{
    LLWebViewController * webview = [[LLWebViewController alloc] init];
    webview.urlStr = [AppDelegate shareAppdelegate].customer_service;
    webview.isType = 1;
    webview.titleStr = @"联系客服";
    [[WJUnit currentViewController].navigationController pushViewController:webview animated:YES];
    

    
}
//联系
- (void)messageClick
{
    MailMainViewController * MailMainVC  = [[MailMainViewController alloc] init];
    MailMainVC.title = @"站内信";
    [self.navigationController pushViewController:MailMainVC animated:YES];
}
- (void)getWallet
{
    if ([DJLoginHelper sharedInstance].is_Login) {
        
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"User_getUserInfos"];
        WeakSelf
        [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
              if (!kStringIsEmpty(responseObject)) {
                  
                  NSError *errorData;
                  NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
                  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
                  if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                      NSLog(@"User_getUserInfos---%@",dict);
                      
                      NSString *balance = kFormat(@"账户余额\n%@元", [NSString stringWithFormat:@"%@",[[dict jsonDict:@"data"]  jsonString:@"property"]]);
                      weakSelf.balance = balance;
                      [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
                  }else{
//                      [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                  }
              }
           
            
        } failure:^(id responseObject, NSError *error) {
            // [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           // [self getWallet];
        }];
    }else
    {
        self.balance = @"登录/注册";
    }
    [self.tableView reloadData];
    
}
#pragma mark----Action数据
/*获取bannes*/
- (void)getbanner
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * banber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getBannerNotice.action"];
    [[SmileHttpTool sharedInstance] GET :banber parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        if (!kStringIsEmpty(responseObject)) {
          NSDictionary * dic = [WJUnit dictionaryWithJsonString:responseObject];
          NSArray * banner = dic[@"data"][@"viwepagers"];
            for (NSDictionary * dic in banner) {
                [weakSelf.banneArray addObject:[NSString stringWithFormat:@"%@%@",imageGameURL,dic[@"background"]]];
            }
            NSArray * notices = dic[@"data"][@"notices"];
            for (NSDictionary * dic in notices) {
                [weakSelf.newsArray addObject:[self ocstringDecode:dic[@"content"]]];
            }
            weakSelf.tableviewHeadView.advertScrollViewCenter.titles = weakSelf.newsArray;
            weakSelf.tableviewHeadView.scrollView.data = weakSelf.banneArray;
        }
        [self stopLoadingAnimation];

    } failure:^(id responseObject, NSError *error) {
        [WJUnit showMessage:@"请求错误"];
        NSLog(@"----%@",error);

    }];
}
- (NSString *)ocstringDecode:(NSString *)str {
    
    return [str stringByRemovingPercentEncoding];
}
//推荐游戏
- (void)getNewslist
{
    
    WeakSelf
    NSString  * banber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGamePlatformlTypeAll"];
    [[SmileHttpTool sharedInstance] GET :banber parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
         if (!kStringIsEmpty(responseObject)) {
             
             
             NSDictionary * dic = [self objectFromJSONString:responseObject];
             NSArray * Games  = [HomeModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
             for (HomeModel * model in  Games)
             {
                 model.image = [WJUnit getGameIcon:model.id];
             }
             NSArray * images = @[@"home_game1",@"home_game2",@"home_game3",@"home_game5"];
             for (int i =0; i<images.count; i++)
             {
                 ClassModel * model = [[ClassModel alloc] init];
                 model.images = images[i];
                 NSMutableArray * dataArray = [NSMutableArray new];
                 if (i ==0)
                 {
                     for (HomeModel * model in Games)
                     {
                         if ([model.type isEqualToString:@"电子游戏"]) {
                             [dataArray addObject:model];
                         }
                     }
                 }else if (i ==1)
                 {
                     for (HomeModel * model in Games)
                     {
                         if ([model.type isEqualToString:@"捕鱼达人"]  ) {
                             [dataArray addObject:model];
                             
                             
                         }
                     }
                 }else if (i ==2)
                 {
                     for (HomeModel * model in Games)
                     {
                         if ([model.type isEqualToString:@"棋牌游戏"]) {
                             [dataArray addObject:model];
                         }
                     }
                 }else if (i ==3)
                 {
                     for (HomeModel * model in Games)
                     {
                         if ([model.type isEqualToString:@"真人娱乐"]) {
                             [dataArray addObject:model];
                         }
                     }
                 }else if (i ==4)
                 {
                    
                     for (HomeModel * model in Games)
                     {
                         if ([model.type isEqualToString:@"足彩竞猜"]) {
                             [dataArray addObject:model];
                         }
                     }
                 }
                 
                 model.dataArray = dataArray;
                 model.isOpen = NO;
                 if (dataArray.count>6) {
                     model.cellHeight = 210;
                 }else if (dataArray.count>0)
                 {
                     model.cellHeight = 140;
                 }else
                 {
                     model.cellHeight = 90;
                 }
                 [weakSelf.dataArray addObject:model];
                 [self.tableView reloadData];
             }
         }
      

    } failure:^(id responseObject, NSError *error) {
        
         [WJUnit showMessage:@"请求错误"];

    }];
   
   
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kStatusBarAndNavigationBarHeight, UIScreenWidth, ContentViewHeight  )style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor = WHITECOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        
        [_tableView registerNib:[UINib nibWithNibName:@"HomeHeadTableViewCell" bundle:nil]  forCellReuseIdentifier:@"HomeHeadTableViewCell"];
        
        [_tableView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil]  forCellReuseIdentifier:@"HomeTableViewCell"];
        _tableView.tableHeaderView =self.tableviewHeadView;
    }
    return _tableView;
}
- (EDHomeTableHeadView*)tableviewHeadView{
    WeakSelf
    if (!_tableviewHeadView) {
        _tableviewHeadView =[[ EDHomeTableHeadView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, headViewHeight)];
    
        //        公告详情
        _tableviewHeadView.Advertblock = ^(NSInteger index) {
            NoticeMessageVC * announceVC = [[NoticeMessageVC alloc] init];
            announceVC.is_HomeMessage =YES;
            //announceVC.index =index;
            announceVC.title = @"最新公告";
            [weakSelf.navigationController pushViewController:announceVC animated:YES];
        };
        //        bancels--URL
        _tableviewHeadView.BancelsUrlblock = ^(NSInteger index) {
//            LLWebViewController *webV = [LLWebViewController new];
//            webV.urlStr = weakSelf.BanneUrlArray[index];
//            webV.isPullRefresh = YES;
//            [weakSelf.navigationController pushViewController:webV animated:YES];
            
        };
        
    }
    return _tableviewHeadView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return _dataArray.count+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0)
    {
        return 75;
    }else
    {
        ClassModel * model = _dataArray[indexPath.row -1];
        if (model.isOpen) {
            return model.cellHeight;
        }else
        {
            return 90;
        }
        
    }
    
    return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0)
    {
        HomeHeadTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"HomeHeadTableViewCell" forIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        [cell.balanceBtn setTitle:self.balance forState:UIControlStateNormal];
        [cell.balanceBtn add_BtnClickHandler:^(NSInteger tag) { //我的资产
            
            
        }];
      
        [cell.depositBtn add_BtnClickHandler:^(NSInteger tag) { //存款
            if (![DJLoginHelper sharedInstance].is_Login)
            {
                [[DJLoginHelper sharedInstance]dj_showLoginVC:self];
            }else
            {
                [AppDelegate shareAppdelegate].index = 0;
                self.navigationController.tabBarController.selectedIndex = 1;
            }
           
        }];
        [cell.withdrawBtn add_BtnClickHandler:^(NSInteger tag) { //提现
            if (![DJLoginHelper sharedInstance].is_Login)
            {
                [[DJLoginHelper sharedInstance]dj_showLoginVC:self];
            }else
            {
                [AppDelegate shareAppdelegate].index = 2;
                self.navigationController.tabBarController.selectedIndex = 1;
            }
           
        }];
        [cell.transferBtn add_BtnClickHandler:^(NSInteger tag) { //转账
            if (![DJLoginHelper sharedInstance].is_Login)
            {
                [[DJLoginHelper sharedInstance]dj_showLoginVC:self];
            }else
            {
                [AppDelegate shareAppdelegate].index = 1;
                self.navigationController.tabBarController.selectedIndex = 1;
            }
           
        }];
        return cell;
    }else
    {
        HomeTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"HomeTableViewCell" forIndexPath:indexPath];
        ClassModel * model = _dataArray[indexPath.row -1];
        cell.gameIcon.image = [UIImage imageNamed:model.images];
        cell.gameView.hidden = YES;
        cell.contentView.backgroundColor = [UIColor whiteColor];
        if (indexPath.row >0 && indexPath.row<5)
        {
           
            if (model.isOpen)
            {
                cell.moreBtn.selected = YES;
                 cell.gameView.height = model.cellHeight - 90;
                [cell addButtonWithGameArray:model.dataArray];
               
                cell.gameView.hidden = NO;
                
                
            }else
            {
                cell.moreBtn.selected = NO;
                cell.gameView.height = 0;
                cell.gameView.hidden = YES;
            }
        }
        WeakSelf
        cell.getGameUrlBlock = ^(HomeModel * _Nonnull modle) {
            [weakSelf getGameURLWithModel:modle];
        };
        [cell.moreBtn add_BtnClickHandler:^(NSInteger tag) {
            
            model.isOpen = !model.isOpen;
            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
        }];
        
        return cell;
    }
  
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassModel * model = _dataArray[indexPath.row -1];
    if (indexPath.row >0 && indexPath.row<5 )
    {
        
        model.isOpen = !model.isOpen;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
        
    }
   
   
}
- (void)getGameURLWithModel:(HomeModel *)model
{
    [self showLoadingAnimation];
    if ([DJLoginHelper sharedInstance].is_Login) {
        NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameUrl"];
        [[SmileHttpTool sharedInstance] GET :game parameters:@{@"mode":@"online",@"gameid":@"110",@"plat_id":model.id,@"gamecode":@""} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
            NSDictionary * dic =[self objectFromJSONString:responseObject];
            [self stopLoadingAnimation];
            if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
            {
                
                LLWebViewController * webview = [[LLWebViewController alloc] init];
                webview.urlStr = dic[@"data"];
                if ([model.type isEqualToString:@"真人娱乐"] || [model.type isEqualToString:@"足彩竞猜"]) {
                    webview.isType = 2;;
                }else
                {
                     webview.isType = 3;
                }
                  webview.isShowGame = YES;
                [self.navigationController pushViewController:webview animated:YES];
            }else
            {
                [WJUnit showMessage:@"请求失败"];
            }
        } failure:^(id responseObject, NSError *error) {
            
            [WJUnit showMessage:@"请求错误"];
             [self stopLoadingAnimation];
        }];
    }else
    {
        [[DJLoginHelper sharedInstance]dj_showLoginVC:self];
    }
   
    
}
@end
